/*
 * @Author: 260156 260156@gree.com.cn
 * @Date: 2022-07-26 08:55:12
 * @LastEditors: 260156 260156@gree.com.cn
 * @LastEditTime: 2022-10-26 15:39:25
 * @FilePath: \gree-zst-web\src\utils\request\index.ts
 * @Description:
 *
 * Copyright (c) 2022 by 260156 260156@gree.com.cn, All Rights Reserved.
 */
import axios from "axios";
// import type {axios} from 'axios'
import { ElMessage, ElMessageBox } from "element-plus";
import type { BasicFetchResult } from "#/request";
import { requireLoginMessageBox } from "../helper";
import type { AxiosRequestConfig } from "axios";
import { RequestMethods } from "./RequestMehods";

const { VITE_BASE } = import.meta.env;

const axiosInstance = axios.create({
  baseURL: VITE_BASE,
});

axiosInstance.interceptors.response.use(
  (response) => {
    const { data: responseData, status: responseStatus, statusText } = response;
    const { desc, status, success, data } = responseData || {};

    if (responseStatus === 200) {
      if (success) {
        return response;
      } else if (status === 401) {
        // localStorage.removeItem('callback') // 清空sessionStorage中的菜单、按钮权限信息
        // sessionStorage.removeItem('state') // 清空sessionStorage中的菜单、按钮权限信息
        localStorage.clear();
        sessionStorage.clear();
        requireLoginMessageBox({ message: desc });
        return Promise.reject(desc || statusText);
      }
    }
    let errorMessage: string = data;
    if (data && typeof data === "object") {
      errorMessage = JSON.stringify(data);
    }
    if (errorMessage) {
      ElMessageBox.alert(errorMessage, "失败", {
        confirmButtonText: "确定",
        type: "error",
      });
      return Promise.reject(errorMessage);
    } else {
      ElMessage.error(desc || statusText);
      return Promise.reject(desc || statusText);
    }
  },
  (error) => {
    let title = "其他错误";
    if (error.response) {
      const { status, statusText: message } = error.response;
      if (status >= 400 && status < 500) {
        title = `${status}: 请求错误`;
      } else if (status >= 500) {
        title = `${status}: 服务器错误`;
      }
      ElMessage.error(title + " - " + message);
      return Promise.reject(error.response);
    } else if (error.message) {
      ElMessage.error(error.message);
      return Promise.reject(error.message);
    } else {
      return Promise.reject(new Error("请求中断"));
    }
  }
);

const axiosRequest = async <T = any>(
  config: AxiosRequestConfig
): Promise<T> => {
  try {
    const {
      data: { data },
    } = await axiosInstance.request<BasicFetchResult<T>>(config);
    return Promise.resolve(data);
  } catch (err) {
    return Promise.reject(err);
  }
};

// 添加request/get/post/put/delete...
const myAxios = new RequestMethods(axiosRequest);

myAxios.get({url: "/loginCallback"})


/**
 * @description: 数据请求
 * 使用方法：
 * myAxios.request(config)  —— 参数与方法axiosRequest一致
 * myAxios.get(config)
 * myAxios.post(config)
 * myAxios.delete(config)
 * myAxios.put(config)
 */
export default myAxios;
